#include "app.h"

#if CONFIG_FREQ_CALIB_ENABLE

#include "attm.h"
#include "gattc_task.h"

void freq_calib_service_init(void)
{
    const struct attm_desc att_db[] =
    {
        {(ATT_DECL_PRIMARY_SERVICE), PERM(RD, ENABLE),            0, 0},
        {(ATT_DECL_CHARACTERISTIC),  PERM(RD, ENABLE),            0, 0},
        {0x0001,                     PERM(WRITE_COMMAND, ENABLE), 0, 128},
    };
    attm_svc_create_db(&app_env.freq_local_handle, 0x01BF, NULL, 3, NULL, TASK_APP, &att_db[0], 0);
    app_env.freq_local_handle += 2;
    log_debug("Frequency calibration handle: 0x%04x", app_env.freq_local_handle);
}

void freq_calib_gattc_write(uint16_t handle, uint8_t *data, uint8_t len)
{
//    struct gattc_write_cmd *p_cmd = KE_MSG_ALLOC_DYN(GATTC_WRITE_CMD, 
//                                                   KE_BUILD_ID(TASK_GATTC,app_env.conidx[0]),
//                                                   app_env.conidx[0], gattc_write_cmd, len);
	
	struct gattc_write_cmd *p_cmd = KE_MSG_ALLOC_DYN(GATTC_WRITE_CMD, 
                                                   KE_BUILD_ID(TASK_GATTC,app_env.conidx),
                                                   app_env.conidx, gattc_write_cmd, len);
	
    p_cmd->operation = GATTC_WRITE_NO_RESPONSE;
    p_cmd->handle = handle;
    p_cmd->length = len;
    memcpy(p_cmd->value, data, len);
    ke_msg_send(p_cmd);
}

void freq_calib_connected_cb(void)
{

}

void freq_calib_disconnected_cb(uint8_t reason)
{
    log_debug("Disconnected. Reason: 0x%02x", reason);
    if (reason == CO_ERROR_REMOTE_DEV_POWER_OFF)
    {
        if (nvds_put(NVDS_TAG_XTAL32M_CTUNE, 1, &app_env.xtal32m_ctune) == NVDS_OK)
        {
            mp_test_report_freq_calib_result();
            log_debug("New frequency offset index: %d", app_env.xtal32m_ctune);
        }
    }
}

void freq_calib_gatt_write_cb(uint16_t handle, uint8_t *data, uint8_t len)
{

    log_debug("Handle = 0x%04x\r\n", handle);
    
    log_debug("data0 = %d\r\n", data[0]);

    log_debug("app_env.freq_calib_start = %d\r\n", app_env.freq_calib_start);
    if (handle == app_env.freq_local_handle)
    {
        
        if(data[0] > 31 || 0 == app_env.freq_calib_start)
        {
            return;
        }
        log_debug("calibration frequence = %d\r\n ",data[0]);
        app_env.xtal32m_ctune = data[0];
        pmu_xtal32m_change_param(app_env.xtal32m_ctune);

        uint8_t buf[] = "hello";
        freq_calib_gattc_write(app_env.freq_peer_handle, buf, sizeof(buf));
    }
}

void freq_calib_get_xtal32m_ctune()
{
    uint8_t xtal32m_ctune;
    nvds_tag_len_t len = 1;
    if (nvds_get(NVDS_TAG_XTAL32M_CTUNE, &len, &xtal32m_ctune) == NVDS_OK)
    {
        if (xtal32m_ctune<=31)
            app_env.xtal32m_ctune = xtal32m_ctune;
    }
    log_debug("Current frequency offset index: %d", app_env.xtal32m_ctune);
}

#endif
